//import Dialog from 'vant/dialog/dialog';
const app = getApp()
const db = wx.cloud.database();
const config = require("../../config.js");
const api = require('../../api/api')
const fmt = require('../../utils/formatTime')
const _ = db.command;
const MAX_QUESTION_LIMIT_SIZE = 10
const MAX_ANSWER_LIMIT_SIZE = 3
const MAX_ANSWER_SHOW_LIMIT_SIZE = 2
let res = {}
let params = {}
let opts = {}
let commodityDetail = {}
let commodity_id = ""
let question_id = ""
let start = 0
let enteredFrom = 1
let commodity_uid = 0
let user_uid = 0
Page({ 

	/**
	 * 页面的初始数据
	 */
	data: {
		isLoading: false,
		hasMore: true,
		showAskPanel: false,
		questionContent: "",
		answerContent: "",
		commodityQuestion: [],
		commodityQuestionCount: 0,
		showAnswerPanel: false,
		showFailPanel: false,
		first_title: true,
		place: '',
	},
	async onLoad(e) {
		console.log(this.data.user_id)
		console.log(app.openid);
		this.getuserdetail();
		this.data.id = e.scene;
		 this.getPublish(e.scene);
		 this.getCommodityQuestionCount(e.scene);
		 this.getCommodityQuestion(e.scene)
		//新增
		const registered = app.globalData.registered
		    opts = e.scene
			start = 0
			
			
      },
      onPullDownRefresh() {
            this.getuserdetail();
		 this.getPublish(this.data.id);
		 this.getCommodityQuestionCount(this.data.id);
		 this.getCommodityQuestion(this.data.id)
      },
	changeTitle(e) {
		let that = this;
		that.setData({
			first_title: e.currentTarget.dataset.id
		})
	},
	//点击提问
	onAskQuestion() {
		console.log(app.openid)
		if (!app.openid) {
			wx.showModal({
				title: '温馨提示',
				content: '该功能需要注册方可使用，是否马上去注册',
				success(res) {
					if (res.confirm) {
						wx.navigateTo({
							url: '/pages/login/login',
						})
					}
				}
			})
			return false
		} else {
			this.setData({
				showAskPanel: true
			})
		}
	},
	// 关闭提问
	onCancelAskPanel() {
		this.setData({
			showAskPanel: false
		})
	},
	//关闭回答
	onCancelAnswerPanel() {
		this.setData({
			showAnswerPanel: false
		})
	},
	//输入提问
	onChangeQuestionContent(event) {
		this.setData({
			questionContent: event.detail.value
		})
		console.log(this.data.questionContent)
	},
	//上传问题
	async onSubmitQuestion() {
		wx.showLoading({
		  title: '提交中',
		})
		params = {
		  commodity_id:this.data.publishinfo._id,
		  content: this.data.questionContent
		}
		res = await api.setCommodityQuestion(params)
		if (res.errno != 0) {
		  wx.hideLoading()
		  console.log("上传信息失败！")
		  wx.showToast({
			title: res.message,
			icon: 'none',
			duration: 2000,
			success(res) {
			  setTimeout(() => {}, 1500)
			}
		  })
		  return
		}
		this.setData({
		  questionContent: "",
		  showAskPanel: false
		})
	
		wx.hideLoading()
		 this.onPullDownRefresh()

	  },
	// 获取商品提问的数量
	async getCommodityQuestionCount(e){
		 params = {
			commodity_id : e,
		  }
		  res = await api.getCommodityQuestionCount(params)
		  if (res.errno == -1) {
			console.log("获取商品问题数量失败！")
			return
		  }
		  const commodityQuestionCount = res.data
		  this.setData({
			commodityQuestionCount
		  })
	},
	//获取商品提问的信息
	async getCommodityQuestion(e){
		start = 0
		params = {
		  commodity_id : e,
		  start: start,
		  count: MAX_QUESTION_LIMIT_SIZE
		}
		res = await api.getCommodityQuestionAndUserInfo(params)
		if (res.errno == -1) {
		  return
		}
		let commodityQuestion = res.data
		start = commodityQuestion.length
		console.log(commodityQuestion)
	
		// 获取每个问题的回答，并加入到commodityQuestion中
		for (let i = 0; i < commodityQuestion.length; i++) {
		  // 问题日期格式化
		  commodityQuestion[i].create_time = fmt(new Date(commodityQuestion[i].create_time))
		  // 回答数量
		  params = { 
			question_id: commodityQuestion[i]._id,
		  }
		  res = await api.getCommodityAnswerCount(params)
		  if (res.errno == -1) {
			console.log("获取问题回答数量失败！")
			return
		  }
		  commodityQuestion[i]["commodityAnswerCount"] = res.data
		  // 回答详情
		  params = {
			question_id: commodityQuestion[i]._id,
			start: 0,
			count: MAX_ANSWER_LIMIT_SIZE
		  }
		  res = await api.getCommodityAnswerAndUserInfo(params)
		  if (res.errno == -1) {
			console.log("获取问题的回答失败！")
			return
		  }
		  let commodityAnswer = res.data
		  commodityQuestion[i]["hasMoreAnswer"] = commodityAnswer.length > MAX_ANSWER_SHOW_LIMIT_SIZE ? true : false
		  commodityQuestion[i]["commodityAnswer"] = commodityAnswer.splice(0, MAX_ANSWER_SHOW_LIMIT_SIZE)
		}
	
		this.setData({
		  commodityQuestion
		})
	},
	//获取发布信息
	getPublish(e) {
		let that = this;
		db.collection('publish').doc(e).get({
			success: function(res) {
				that.setData({
					collegeName: JSON.parse(config.data).college[parseInt(res.data.collegeid) + 1],
					publishinfo: res.data,
					user_id : res.data._openid

				})
				that.getSeller(res.data._openid, res.data.bookinfo._id)
			}
		})
	},
	//点击回复
	onAnswerQuestion(e){
		question_id = e.currentTarget.dataset.questionid
		console.log(app.openid)
		if (!app.openid) {
			wx.showModal({
				title: '温馨提示',
				content: '该功能需要注册方可使用，是否马上去注册',
				success(res) {
					if (res.confirm) {
						wx.navigateTo({
							url: '/pages/login/login',
						})
					}
				}
			})
			return false
		} else {
			this.setData({
				showAnswerPanel: true,
			})
		}
	},
	//回复内容
	onChangeAnswerContent(e){
		this.setData({
			answerContent: e.detail.value
		  })
	},
	//上传回复
	async onSubmitAnswer(){
		wx.showLoading({
			title: '提交中',
		  })
		  params = {
			question_id,
			commodity_id:this.data.publishinfo._id,
			content: this.data.answerContent
		  }
		  res = await api.setCommodityAnswer(params)
		  if (res.errno != 0) {
			wx.hideLoading()
			console.log("上传信息失败！")
			wx.showToast({
			  title: res.message,
			  icon: 'none',
			  duration: 2000,
			  success(res) {
				setTimeout(() => {}, 1500)
			  }
			})
			return
		  }
		  this.setData({
			answerContent: "",
			showAnswerPanel: false
		  })
		  wx.hideLoading()
		   this.onPullDownRefresh()
	},
	
	//获取卖家信息
	getSeller(m, n) {
		let that = this;
		db.collection('user').where({
			_openid: m
		}).get({
			success: function(res) {
				that.setData({
					userinfo: res.data[0]
				})
				that.getBook(n)
			}
		})
	},
	//获取书本信息
	getBook(e) {
		let that = this;
		db.collection('books').doc(e).get({
			success: function(res) {
				that.setData({
					bookinfo: res.data
				})
			}
		})
	},
	//回到首页
	home() {
		wx.switchTab({
			url: '/pages/index/index',
		})
	},
	//购买检测
	buy() {

		let that = this;
		if (!app.openid) {
			wx.showModal({
				title: '温馨提示',
				content: '该功能需要注册方可使用，是否马上去注册',
				success(res) {
					if (res.confirm) {
						wx.navigateTo({
							url: '/pages/login/login',
						})
					}
				}
			})
			return false
		}
		if(that.data.user_id == app.openid) {
			wx.showToast({
				title:"不能购买自己发布的商品",
				icon:'none'
			})
			return false

		}
		
		if (that.data.publishinfo.deliveryid != 0) {
			if (that.data.place == '') {
				wx.showToast({
					title: '请输入您的收货地址',
					icon: 'none'
				})
				return false
			}
			//that.getStatus();
		}
		that.getStatus();
	},
	//获取订单状态
	getStatus() {
		let that = this;
		let _id = that.data.publishinfo._id;
		db.collection('publish').doc(_id).get({
			success(e) {
				if (e.data.status == 0) {
//跳过支付，直接生成订单
					that.setStatus();
				} else {
					wx.showToast({
						title: '该书刚刚被抢光了~',
						icon: 'none'
					})
				}
			}
		})
	},
	//支付提交
	// paypost() {
	// 	let that = this;
	// 	wx.showLoading({
	// 		title: '正在下单',
	// 	});
	// 	// 利用云开发接口，调用云函数发起订单
	// 	wx.cloud.callFunction({
	// 		name: 'pay',
	// 		data: {
	// 			$url: "pay", //云函数路由参数
	// 			goodId: that.data.publishinfo._id
	// 		},
	// 		success: res => {
	// 			wx.hideLoading();
	// 			that.pay(res.result)
	// 		},
	// 		fail(e) {
	// 			wx.hideLoading();
	// 			wx.showToast({
	// 				title: '支付失败，请及时反馈或稍后再试',
	// 				icon: 'none'
	// 			})
	// 		}
	// 	});
	// },
	//实现小程序支付
	// pay(payData) {
	// 	let that = this;
	// 	//官方标准的支付方法
	// 	wx.requestPayment({
	// 		timeStamp: payData.timeStamp,
	// 		nonceStr: payData.nonceStr,
	// 		package: payData.package, //统一下单接口返回的 prepay_id 格式如：prepay_id=***
	// 		signType: 'MD5',
	// 		paySign: payData.paySign, //签名
	// 		success(res) {
	// 			that.setStatus();
	// 		},
	// 	})
	// },
	//修改卖家在售状态
	setStatus() {
		let that = this
		wx.showLoading({
			title: '正在处理',
		})
		// 利用云开发接口，调用云函数发起订单
		wx.cloud.callFunction({
			name: 'pay',
			data: {
				$url: "changeP", //云函数路由参数
				_id: that.data.publishinfo._id,
				status: 1
			},
			success: res => {
				console.log('修改订单状态成功')
				that.creatOrder();
			},
			fail(e) {
				wx.hideLoading();
				wx.showToast({
					title: '发生异常，请及时和管理人员联系处理',
					icon: 'none'
				})
			}
		})
	},
	//创建订单
	creatOrder() {
		let that = this;
		db.collection('order').add({
			data: {
				creat: new Date().getTime(),
				status: 1, //0在售；1买家已付款，但卖家未发货；2买家确认收获，交易完成；3、交易作废，退还买家钱款
				price: that.data.publishinfo.price, //售价
				deliveryid: that.data.publishinfo.deliveryid, //0自1配
				ztplace: that.data.publishinfo.place, //自提时地址
				psplace: that.data.place, //配送时买家填的地址
				bookinfo: {
					_id: that.data.bookinfo._id,
					author: that.data.bookinfo.author,
					edition: that.data.bookinfo.edition,
					pic: that.data.bookinfo.pic,
					title: that.data.bookinfo.title,
				},
				seller: that.data.publishinfo._openid,
				sellid: that.data.publishinfo._id,
			},
			success(e) {
				that.history('购买书籍', that.data.publishinfo.price, 2, e._id)
			},
			fail() {
				wx.hideLoading();
				wx.showToast({
					title: '发生异常，请及时和管理人员联系处理',
					icon: 'none'
				})
			}
		})
	},
	//路由
	go(e) {
		wx.navigateTo({
			url: e.currentTarget.dataset.go,
		})
	},
	//地址输入
	placeInput(e) {
		this.data.place = e.detail.value
	},
	onShareAppMessage() {
		return {
			title: '这本《' + this.data.bookinfo.title + '》只要￥' + this.data.publishinfo.price + '元，快来看看吧',
			path: '/pages/detail/detail?scene=' + this.data.publishinfo._id,
		}
	},
	//历史记录
	//记录两次，一次相当于使用微信支付充值，一次是用于购买书籍付款
	history(name, num, type, id) {
		let that = this;
		db.collection('history').add({
			data: {
				stamp: new Date().getTime(),
				type: 1, //1充值2支付
				name: '微信支付',
				num: num,
				oid: app.openid,
			},
			success: function(res) {
				db.collection('history').add({
					data: {
						stamp: new Date().getTime(),
						type: type, //1充值2支付
						name: name,
						num: num,
						oid: app.openid,
					},
					success: function(res) {
						wx.hideLoading();
						//that.sms();
						that.tip();
						wx.redirectTo({
							url: '/pages/success/success?id=' + id,
						})
					}
				})
			},
		})
	},
	//短信提醒
	// sms() {
	// 	let that = this;
	// 	wx.cloud.callFunction({
	// 		name: 'sms',
	// 		data: {
	// 			mobile: that.data.userinfo.phone,
	// 			title: that.data.bookinfo.title,
	// 		},
	// 		success: res => {
	// 			console.log(res)
	// 		},
	// 	})
	// },
	//邮件提醒收货
	tip() {
		let that = this;
		wx.cloud.callFunction({
			name: 'email',
			data: {
				type: 1, //1下单提醒2提醒收货
				email: that.data.userinfo.email,
				title: that.data.bookinfo.title,
			},
			success: res => {
				console.log(res)
			},
		})
	},
	//为了数据安全可靠，每次进入获取一次用户信息
	getuserdetail() {
		if (!app.openid) {
			wx.cloud.callFunction({
				name: 'regist',
				data: {
					$url: "getid",
				},
				success: re => {
					db.collection('user').where({
						_openid: re.result
					}).get({
						success: function(res) {
							if (res.data.length !== 0) {
								app.openid = re.result;
								app.userinfo = res.data[0];
								console.log(app)
							}
							console.log(res)
						}
					})
				}
			})
		}
	},

	//客服跳动动画
	kefuani: function() {
		let that = this;
		let i = 0
		let ii = 0
		let animationKefuData = wx.createAnimation({
			duration: 1000,
			timingFunction: 'ease',
		});
		animationKefuData.translateY(10).step({
			duration: 800
		}).translateY(0).step({
			duration: 800
		});
		that.setData({
			animationKefuData: animationKefuData.export(),
		})
		setInterval(function() {
			animationKefuData.translateY(20).step({
				duration: 800
			}).translateY(0).step({
				duration: 800
			});
			that.setData({
				animationKefuData: animationKefuData.export(),
			})
			//++ii;
			// console.log(ii);
		}.bind(that), 1800);
	},
	onReady() {
		this.kefuani();
	}
})
